#encoding:utf8
from django.shortcuts import render_to_response
from django.http import HttpResponseRedirect
from web.forms import MonitorForm,SelectMonitor,ClientMonitor
import sys,time,os
sys.path.append('/cihi/app/include')
import init,api

k = init.INIT()
workdir = k.WorkDir_web

def monitorstatus(request):    #监控数据 页面
    monitoralias = {}
    alldata = {}
    imgmonitor = ['check_traffic','check_load','check_mem','check_disk','check_procs','check_ping','check_openfiles','check_tcpconnect']
    lastmonitor = k.getHash('lastmonitor')
    if not lastmonitor.get('time'):return render_to_response('monitorstatus.html',locals())
    hostlist = k.getClientList()
    monitorlist = k.getMonitorList()
    lastmonitor['errorinfo'] = eval(lastmonitor['errorinfo'])
    monitorlist.append('get_time')
    gettime = time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(float(lastmonitor['time'])))
    nowtime = time.strftime('%Y-%m-%d %H:%M:%S')
    
    for monitor in monitorlist:
        monitoralias[monitor] = k.getMonitorAtt(monitor)
    monitoralias.update({'get_time':{'monitoralias':'获取时间'}})
    for host in k.getClientList('bad'):
        k.saveSSet('cihi_client',host,1)
    for host in hostlist:
        dic = k.getHash('lastmonitor',host)
        if dic == None:
            continue
        else:
            alldata[host] = api.format(eval(dic))
        for monitor in alldata[host]:
            if alldata[host][monitor]['color'] == 'red':
                k.saveSSet('cihi_client',host,10000)
                break
    okhostlist = k.getClientList('ok')
    badhostlist = k.getClientList('bad')
    return render_to_response('monitorstatus.html',locals())

def monitorlist(request):    #监控配置  页面
    result = []
    for monitor in k.getMonitorList():
        tmp = k.getMonitorAtt(monitor)
        tmp['monitorname'] = monitor
        result.append(tmp)
    return render_to_response('monitor.html',locals())

def monitorconf(request,param):    #监控配置 添加、编辑、删除 页面
    if param == 'del':
        k.delMonitor(request.GET.get('monitor'))
        return HttpResponseRedirect('/monitor')
    elif param == 'edit':
        monitor = request.GET.get('monitor')
        default = k.getMonitorAtt(monitor)
        default['monitorname'] = monitor
    else:
        default = {}
    if request.method == 'POST':
        form = MonitorForm(request.POST)
        if form.is_valid():
            error = ''
            result = form.cleaned_data
            monitor = result['monitorname']
            if param == 'add':
                if monitor in k.getMonitorList():error = u'该项目已存在。'
            else:
                if monitor != request.GET.get('monitor'):error = u'不允许编辑监控项目。'
            if error:
                form.errors['monitorname'] = [error]
            else:
                if result['monitortype'] == 'client':
                    k.saveSSet('cihi_monitor',monitor,10000)
                else:
                    k.saveSSet('cihi_monitor',monitor)
                del result['monitorname']
                k.saveHash(monitor+'_att',result)
                return HttpResponseRedirect('/monitor/')
    else:
        form = MonitorForm(initial=default,label_suffix='')
    return render_to_response('addmonitor.html',locals())

def clientmonitor(request,param):    #主机配置 的 监控配置 页面
    host = request.GET.get('host')
    monitor = request.GET.get('monitor')
    if monitor:
        default = k.getClientHavMonitor(host)
        if request.method == 'GET':
            if monitor == 'Null':
                for monitor in default:
                    k.delSet(monitor+'_hostlist',host)
                return HttpResponseRedirect('/client/')
            default = k.getClientMonitor(host)
            form = ClientMonitor(initial=default,label_suffix='')
        else:
            form = ClientMonitor(request.POST)
            if form.is_valid():
                result = form.cleaned_data
                monitorlist = eval(k.getKey('cihimonitor_temp'))
                addmonitor = [ val for val in monitorlist if val not in default ]
                delmonitor = [ val for val in default if val not in monitorlist ]
                for monitor in addmonitor:
                    k.saveSet(monitor+'_hostlist',host)
                for monitor in delmonitor:
                    k.delSet(monitor+'_hostlist',host)
                k.saveHash(host+'_monitor',result)
                return HttpResponseRedirect('/client/')
        return render_to_response('clientmonitor.html',locals())
        
    if request.method == 'POST':
        form = SelectMonitor(request.POST)
        if form.is_valid():
            result = form.cleaned_data
            if result['monitor']:
                k.saveKey('cihimonitor_temp',result['monitor'])
                return HttpResponseRedirect('/client/monitor/edit/?host=%s&monitor=True' % host)   
            else:
                return HttpResponseRedirect('/client/monitor/edir/?host=%s&monitor=Null' % host)
    else:
        form = SelectMonitor(initial={'monitor':k.getClientHavMonitor(host)},label_suffix='')
    return render_to_response('clientmonitor.html',locals())
